package com.dongdongshop.controller;

import com.dongdongshop.em.ConstantEnum;
import com.dongdongshop.pojo.StatusCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedHashMap;
import java.util.Map;
@Controller
@RequestMapping("loginController")
public class LoginController {
    //登录
    @RequestMapping("loginInfo")
    @ResponseBody
    public StatusCode loginInfo(String username, String password) {
        Map<String, Object> map = new LinkedHashMap<>();
        if (username == null && password == null) {
            return StatusCode.build(ConstantEnum.NULL_ERROR);
        }
        //1.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.封装token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3.调用登陆方法
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            map.put("messg", "用户名不存在");
            return StatusCode.build(ConstantEnum.ERROR).setT(map);
        } catch (IncorrectCredentialsException e) {
            map.put("messg", "密码错误");
            return StatusCode.build(ConstantEnum.ERROR).setT(map);
        }
        map.put("messg", "登陆成功");
        return StatusCode.build(ConstantEnum.SUCCESS).setT(map);
    }

}
